// Modules to control application life and create native browser window
const {app, BrowserWindow, ipcMain} = require('electron')
const path = require('path')

var net = require('net')
// 检测端口是否被占用
function portIsOccupied (port, onSuccess, onError) {
  // 创建服务并监听该端口
  var server = net.createServer().listen(port)

  server.on('listening', function () { // 执行这块代码说明端口未被占用
    server.close() // 关闭服务
    console.log('The port[' + port + '] is available.') // 控制台输出信息

    onSuccess()
  })

  server.on('error', function (err) {
    if (err.code === 'EADDRINUSE') { // 端口已经被使用
      console.log('The port[' + port + '] is occupied, please change other port.')

      onError()
    }
  })
}
var ip = require('ip')

ipcMain.on('newModal',(e,arg)=> {
  console.log('receive command')

  let port = 3200

  portIsOccupied(port, function () {
    const startServer = require('./server/index')
    startServer()
  }, function () {

  })

  mainWindow.webContents.send('receive', `http://${ip.address()}:${port}`)

})

let mainWindow
function createWindow () {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 1200,
    height: 720,
    autoHideMenuBar: true,
    webPreferences: {
      nodeIntegration: true,
      preload: path.join(__dirname, 'preload.js')
    }
  })

  // and load the index.html of the app.
  // mainWindow.loadFile('front/dist/index.html')
  if (process.env.NODE_ENV === 'dev') {
    mainWindow.loadURL('http://localhost:8080')
    // Open the DevTools.
    mainWindow.webContents.openDevTools()
  } else {
    mainWindow.loadFile('front/dist/index.html')
  }


  mainWindow.webContents.on('did-finish-load',function(){


  });

}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(createWindow)

app.on('ready', () => {
  // if (process.env.NODE_ENV !== 'production') {
  //   require('vue-devtools').install()
  // }
})

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') app.quit()
})

app.on('activate', function () {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
